package zhuyun.code.launcheractivity.utils

import android.graphics.Bitmap
import android.text.TextUtils
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import com.google.zxing.Result
import java.nio.charset.Charset
import java.util.*



/**
 * @author: Administrator
 * @date: 2021/11/24
 */
object QRHelper {
    fun getResult(bitmap:Bitmap):String?{
        var string:String? = null
        bitmap?.let {
            string = scanBitmap(it)
        }
        if(!TextUtils.isEmpty(string)){
            return string
        }
        return null
    }

    private fun scanBitmap(bitmap: Bitmap):String{
        val result = scan(bitmap)
        return recode(result.toString())
    }

    private fun recode(str:String):String{
        var format =""
        val iso = Charset.forName("ISO-8859-1").newEncoder().canEncode(str)
        format = if(iso){
            str.toByteArray(Charsets.ISO_8859_1).toString(Charset.forName("GB2312"))
        } else {
            str
        }
        return format
    }

    private fun scan(bitmap: Bitmap): Result {
        val px = IntArray(bitmap.width*bitmap.height){_->0}
        bitmap.getPixels(px,0,bitmap.width,0,0,bitmap.width,bitmap.height)
        val source = RGBLuminanceSource(bitmap.width,bitmap.height,px)
        val tempBitmap = BinaryBitmap(HybridBinarizer(source))
        val reader = QRCodeReader()
        val hints = Hashtable<DecodeHintType,String>()
        hints[DecodeHintType.CHARACTER_SET] = "utf-8"
        return reader.decode(tempBitmap,hints)
    }

}